package com.bigknow.appstore.web.util;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.function.Predicate;

/**
 * Created by 李科风 on 2016-10-13.
 */
public class UploadFileUtils {

    public static String saveImage(CommonsMultipartFile bannerFile, String dir, String id, Predicate<BufferedImage> action) {
        String webRoot = System.getProperty("web.root");
        File bannerDir = new File(webRoot, dir);
        bannerDir.mkdirs();
        File tempFile = null;
        File file = null;
        try {
            tempFile = File.createTempFile("temp", "img");
            bannerFile.transferTo(tempFile);
            file = new File(bannerDir, id + "." + ImageUtils.getFormatName(tempFile));
            BufferedImage imageFile = ImageIO.read(tempFile);
            action.test(imageFile);
            FileUtils.copyFile(tempFile, file);
            return file.getName();
        } catch (IOException e) {
            FileUtils.deleteQuietly(file);
            throw new RuntimeException(e);
        } finally {
            FileUtils.deleteQuietly(tempFile);
        }
    }

    public static void deleteImage(String dir, String file) {
        if (StringUtils.isEmpty(file)) {
            return;
        }
        String webRoot = System.getProperty("web.root");
        File parentDir = new File(webRoot, dir);
        FileUtils.deleteQuietly(new File(parentDir, file));
    }
}
